// models/WritingRecord.js - 自动统计版本
const mongoose = require('mongoose');

const writingRecordSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  date: {
    type: Date,
    required: true,
    index: true
  },
  // 自动统计字段
  wordCount: {
    type: Number,
    default: 0,
    min: 0
  },
  // 关联作品信息
  novelId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Novel'
  },
  chapterId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Chapter'
  },
  // 统计来源
  source: {
    type: String,
    enum: ['chapter_publish', 'chapter_update', 'manual'],
    default: 'manual'
  },
  // 自动计算的写作时间（基于章节创建和更新时间）
  estimatedWritingTime: {
    type: Number, // 分钟
    min: 0
  },
  // 统计元数据
  metadata: {
    chapterTitle: String,
    novelTitle: String,
    publishTime: Date,
    wordCountBefore: Number, // 更新前的字数（用于计算增量）
    wordCountAfter: Number   // 更新后的字数
  }
}, {
  timestamps: true
});

// 复合索引
writingRecordSchema.index({ userId: 1, date: 1 });
writingRecordSchema.index({ userId: 1, novelId: 1, date: 1 });

// 静态方法：自动创建或更新写作记录
writingRecordSchema.statics.autoCreateRecord = async function(userId, chapterData) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  
  // 计算估算的写作时间（基于章节创建和更新时间）
  let estimatedTime = 0;
  if (chapterData.createdAt && chapterData.updatedAt) {
    const timeDiff = new Date(chapterData.updatedAt) - new Date(chapterData.createdAt);
    estimatedTime = Math.max(1, Math.round(timeDiff / (1000 * 60))); // 转换为分钟
  }
  
  // 查找今天的记录
  const existingRecord = await this.findOne({
    userId,
    date: today,
    chapterId: chapterData._id
  });
  
  if (existingRecord) {
    // 更新现有记录
    const wordCountIncrement = chapterData.wordCount - existingRecord.metadata.wordCountAfter;
    
    return await this.findByIdAndUpdate(existingRecord._id, {
      wordCount: existingRecord.wordCount + Math.max(0, wordCountIncrement),
      estimatedWritingTime: estimatedTime,
      'metadata.wordCountAfter': chapterData.wordCount,
      'metadata.publishTime': new Date()
    }, { new: true });
  } else {
    // 创建新记录
    return await this.create({
      userId,
      date: today,
      wordCount: chapterData.wordCount,
      novelId: chapterData.novelId,
      chapterId: chapterData._id,
      source: 'chapter_publish',
      estimatedWritingTime: estimatedTime,
      metadata: {
        chapterTitle: chapterData.title,
        novelTitle: chapterData.novelTitle,
        publishTime: new Date(),
        wordCountBefore: 0,
        wordCountAfter: chapterData.wordCount
      }
    });
  }
};

module.exports = mongoose.model('WritingRecord', writingRecordSchema);